package org.atlantis.mina.demo2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MinaTimeServer {

	public static void main(String[] args) throws IOException {
		IoAcceptor acceptor = new NioSocketAcceptor();

		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		// ProtocolCodecFilter会将二进制或特殊格式的数据转换成一个消息对象（同样，反过来也能将消息对象还原为二进制或特殊格式的数据）
		acceptor.getFilterChain().addLast(
				"codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(Charset
						.forName("UTF-8"))));

		acceptor.setHandler(new TimeServerHandler());

		// 设置的buffer size是告诉底层操作系统要分配多少空间给接收到的数据，一般不用设置Mina会自动调节
		acceptor.getSessionConfig().setReadBufferSize(2048);
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

		// 启动服务器，监听两个端口：8888和9999
		acceptor.bind(new InetSocketAddress(8888));
		acceptor.bind(new InetSocketAddress(9999));
		System.out.println("Time Server started! listen port at : 8888 and 9999");
	}
}
